Imports System.Data

Imports System.Configuration
Imports DAL
Imports Microsoft.VisualBasic.Strings
Imports MyClasses


Public Class frmDatabaseRestore
    'Dim OledbConnectionString As String
    Public bBackRestore As New BBackup
    'Dim oScript As New clsScript
    Public FileExtension As String = "SQLBackup"
    'Dim DTObjects As New DataTable
    Sub SetProgress(ByVal iVal As Integer)
        ProgressBar1.Value = iVal
        Me.Refresh()
    End Sub
    Sub ShowProgressBar()
        ProgressBar1.Visible = True
        lblPleasewait.Visible = True
    End Sub
    Sub HideProgressBar()
        ProgressBar1.Visible = False
        lblPleasewait.Visible = False
    End Sub
    Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
        Me.Close()
    End Sub

    Private Sub frmDatabaseRestore_HelpButtonClicked(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.HelpButtonClicked
        'Rauhl_ITS@20073012 : Add following code display help
        Help.ShowHelp(Me, "Pharma.chm", HelpNavigator.KeywordIndex, "Restore Database")
        e.Cancel = True
    End Sub

    Private Sub frmDatabaseRestore_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
        If e.KeyCode = Keys.F1 Then
            e.SuppressKeyPress = True
            Help.ShowHelp(Me, "Pharma.chm", HelpNavigator.KeywordIndex, "Restore Database")
        End If
    End Sub
    Private Sub frmDatabaseRestore_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Call BCommon.SetFormStandards(Me)
        HideProgressBar()
        txtBackupFile.Text = ""
        'LoadSettingsFrom(My.Application.Info.DirectoryPath + "\DefaultValues.restoresettings")
        'txtBackupDir.Text = My.Application.Info.DirectoryPath + "\Temp\" + Format(DateTime.Now, "ddMMyyhhmmss") + "\"
        '        txtBackupDir.Text = "D:\Temp\" + Format(DateTime.Now, "ddMMyyhhmmss") + "\"
        txtBackupDir.Text = My.Application.Info.DirectoryPath.Substring(0, 2) + "\Temp\" + Format(DateTime.Now, "ddMMyyhhmmss") + "\"
        If My.Computer.FileSystem.DirectoryExists(txtBackupDir.Text) Then
            My.Computer.FileSystem.DeleteDirectory(txtBackupDir.Text, FileIO.DeleteDirectoryOption.DeleteAllContents)
        End If
        ''CREATE TEMPORARY DIRECTORY.
        If Not My.Computer.FileSystem.DirectoryExists(txtBackupDir.Text) Then
            My.Computer.FileSystem.CreateDirectory(txtBackupDir.Text)
        End If
        'oScript.ConnectServer("(local)", "", "")
        '        bBackRestore.ConnectServer(ConfigurationManager.AppSettings("Server"), ConfigurationManager.AppSettings("UID"), ConfigurationManager.AppSettings("PWD"))
    End Sub
    Sub LoadSettingsFrom(ByVal sFileName As String)
        Dim DS As New DataSet
        Try
            If My.Computer.FileSystem.FileExists(sFileName) Then
                DS.ReadXml(sFileName)
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "LoadSettingsFrom")
        End Try
    End Sub
    Private Sub cmdOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOpenFile.Click
        Dim sFile As String = AskOpenFile()

        Try
            If sFile <> "" Then
                txtBackupFile.Text = sFile

            Else
                Exit Sub
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmdOpenFile_Click")
        End Try
    End Sub
    Public Function AskOpenFile() As String
        Dim fileD As New OpenFileDialog
        Try
            fileD.Filter = "SQLBackup Files | *." + FileExtension
            If fileD.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Return fileD.FileName
            Else
                Return ""
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "AskOpenFile")
            Return ""
        End Try
    End Function
    'Private Sub cmdConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
    '    ShowProgressBar()
    '    ProgressBar1.Maximum = 8
    '    SetProgress(1)
    '    Me.Refresh()
    '    'Connect_To_Database()
    '    HideProgressBar()
    'End Sub
    'Sub Connect_To_Database()
    '    Try
    '        SetProgress(3)
    '        Dim DS As New DataSet

    '        DS.ReadXml(txtBackupDir.Text + "SQLScripts.xml")
    '        If DS.Tables.Count > 0 Then
    '            Dim DT As DataTable = DS.Tables(0)
    '            DT.PrimaryKey = New DataColumn() {DT.Columns("ObjectName")}
    '            DT.DefaultView.RowFilter = "ObjectType='table'"
    '            'If chkMaster.Checked = False And chkTrans.Checked = False Then
    '            Get_Objects(DT, dgTables, "TableName")
    '            'End If
    '            SetProgress(8)
    '        End If
    '    Catch ex As Exception
    '        MessageBox.Show(ex.ToString())
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "Connect_To_Database")
    '    End Try
    'End Sub

    'Sub Get_Objects(ByRef DT As DataTable, ByRef dg As DataGridView, ByVal ObjectTypeName As String)
    '    Try
    '        Dim str As String, str1 As String
    '        Dim strMaster, strTrans
    '        Dim intDtRows As Integer
    '        Dim intCount As Integer, intCount1 As Integer
    '        Dim DTObjects As New DataTable

    '        DTObjects.Columns.Add(ObjectTypeName, "".GetType)
    '        DTObjects.Columns.Add("Select", True.GetType)
    '        DTObjects.Columns.Add("ScriptSQL", "".GetType)
    '        DTObjects.Columns.Add("Status", "".GetType)

    '        If chkMaster.Checked = False And chkTrans.Checked = False Then
    '            'DTObjects.Rows.Add(New Object() {DT.DefaultView(intDtRows)("TableName"), True, DT.DefaultView(intDtRows)("ScriptSQL")})
    '            For intDtRows = 0 To DT.DefaultView.Count - 1
    '                DTObjects.Rows.Add(New Object() {DT.DefaultView(intDtRows)("ObjectName"), True, DT.DefaultView(intDtRows)("ScriptSQL")})
    '            Next
    '        End If
    '        If chkMaster.Checked = True Then
    '            str = ConfigurationManager.AppSettings("Master")
    '            strMaster = Split(str, ",")
    '            'Dim strMList(UBound(strMaster))
    '            For intCount = 0 To UBound(strMaster)
    '                Dim myRow As System.Data.DataRow = DT.Rows.Find(strMaster(intCount))
    '                If IsNothing(myRow) Then
    '                    'not found
    '                Else
    '                    DTObjects.Rows.Add(New Object() {myRow.Item("ObjectName"), True, myRow.Item("ScriptSQL")})
    '                End If
    '            Next
    '        End If
    '        If chkTrans.Checked = True Then
    '            str1 = ConfigurationManager.AppSettings("Transaction")
    '            strTrans = Split(str1, ",")
    '            'Dim strTList(UBound(strTrans))
    '            For intCount1 = 0 To UBound(strTrans)
    '                Dim myRow As System.Data.DataRow = DT.Rows.Find(strTrans(intCount1))
    '                If IsNothing(myRow) Then
    '                    'not found
    '                Else
    '                    DTObjects.Rows.Add(New Object() {myRow.Item("ObjectName"), True, myRow.Item("ScriptSQL")})
    '                End If
    '            Next
    '        End If
    '        dg.DataSource = DTObjects
    '        Format_Grid(dg)
    '    Catch ex As Exception
    '        'MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "Get_Objects")
    '    End Try
    'End Sub
    'Public Sub Format_Grid(ByRef dg As DataGridView)
    '    Dim i As Integer
    '    Try
    '        If Not IsNothing(dg.DataSource) Then
    '            For i = 0 To dg.Columns.Count - 1
    '                If i = 0 Then
    '                    dg.Columns(0).Width = 200
    '                    dg.Columns(0).ReadOnly = True
    '                End If
    '                If i = 1 Then
    '                    dg.Columns(1).Width = 80
    '                    dg.Columns(1).ReadOnly = False
    '                End If
    '                If i = 2 Then
    '                    dg.Columns(2).Width = 150
    '                    dg.Columns(2).ReadOnly = False
    '                    If dg.Columns(2).Name = "ScriptSQL" Then
    '                        dg.Columns(2).Visible = False
    '                    End If
    '                    If dg.Columns(2).Name = "Status" Then
    '                        dg.Columns(2).ReadOnly = True
    '                    End If
    '                End If
    '                If i = 3 Then
    '                    dg.Columns(3).Width = 200
    '                    dg.Columns(3).ReadOnly = False
    '                End If
    '                If i = 4 Then
    '                    dg.Columns(4).Width = 200
    '                    dg.Columns(4).ReadOnly = False
    '                    dg.Columns(4).Visible = False
    '                End If
    '                If i = 5 Then
    '                    dg.Columns(5).Width = 200
    '                    If dg.Columns(5).Name = "Status" Then
    '                        dg.Columns(5).ReadOnly = True
    '                    End If
    '                End If
    '            Next
    '            dg.RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    '            dg.AllowUserToAddRows = False
    '            dg.AllowUserToDeleteRows = False
    '            dg.AllowUserToResizeRows = False
    '        End If
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "Format_Grid")
    '    End Try
    'End Sub
    Private Sub cmdExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExport.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            If My.Computer.FileSystem.DirectoryExists(txtBackupDir.Text) Then
                My.Computer.FileSystem.DeleteDirectory(txtBackupDir.Text, FileIO.DeleteDirectoryOption.DeleteAllContents)
            End If
            ''CREATE TEMPORARY DIRECTORY.
            If Not My.Computer.FileSystem.DirectoryExists(txtBackupDir.Text) Then
                My.Computer.FileSystem.CreateDirectory(txtBackupDir.Text)
            End If

            cmdExport.Enabled = False
            If Trim(txtBackupFile.Text) = "" Then
                'MessageBox.Show("Please select a backup file to restore.", "Select Backup File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                MessageBox.Show(BCommon.GetMessage(10390), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                cmdExport.Enabled = True
                Exit Sub
            End If

            If Not My.Computer.FileSystem.FileExists(txtBackupFile.Text) Then
                'MessageBox.Show("Specified backup file does not exists.", "File not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                MessageBox.Show(BCommon.GetMessage(10391), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                cmdExport.Enabled = True
                Exit Sub
            End If


            ShowProgressBar()
            ProgressBar1.Maximum = 8
            SetProgress(4)
            Dim ByteRestoreAct As Byte
            ByteRestoreAct = bBackRestore.RestoreAction(True, False, False, True, False, txtBackupFile.Text, txtBackupDir.Text)

            'If bBackRestore.RestoreAction(chkStructure.Checked, chkMaster.Checked, chkTrans.Checked, txtBackupFile.Text, txtBackupDir.Text) = 1 Then
            If ByteRestoreAct = 1 Then
                'MessageBox.Show("Database restore complete", "Restore Complete", MessageBoxButtons.OK, MessageBoxIcon.Information)
                SetProgress(6)
                MessageBox.Show(BCommon.GetMessage(10392), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.OK, MessageBoxIcon.Information)
                SetProgress(8)
                cmdExport.Enabled = True
                HideProgressBar()
                Global.System.Windows.Forms.Application.Exit()
                'Me.Close()
            ElseIf ByteRestoreAct = 2 Then
                'MessageBox.Show("Problem in Database Restore", "Restore Complete", MessageBoxButtons.OK, MessageBoxIcon.Information)
                MessageBox.Show(BCommon.GetMessage(10393), ConfigurationManager.AppSettings("MsgTitle"), MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            'Dim ansCreateDB = vbNo

            'Dim IsDBExists As Boolean = bBackRestore.IsDatabaseExists(ConfigurationManager.AppSettings("DbName"))

            'bBackRestore.ConnectServer(ConfigurationManager.AppSettings("Server"), ConfigurationManager.AppSettings("UID"), ConfigurationManager.AppSettings("PWD"))

            'bBackRestore.DropDatabase(ConfigurationManager.AppSettings("DbName"))

            'bBackRestore.CreateNewDatabase(ConfigurationManager.AppSettings("DbName"))


            'ShowProgressBar()
            'ProgressBar1.Maximum = 8
            'SetProgress(1)
            'Me.Refresh()
            'bBackRestore.ConnectDatabaseWithRefresh()

            'If chkData.Checked = False And chkStructure.Checked = False Then
            '    MessageBox.Show("Please select structure or data to restore.", "Check", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            '    Exit Sub
            'End If

            'Export_Database()
            'HideProgressBar()
            Me.Cursor = Cursors.Default
        Catch ex As Exception
            'MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmdExport_Click")
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    'Sub Export_Database()
    '    Try
    '        Dim str As String, str1 As String
    '        Dim strMaster, strTrans
    '        Dim intCount As Integer
    '        If chkStructure.Checked Then
    '            If DTObjects.Rows.Count > 0 Then
    '                DTObjects.Columns.Add("Executed", False.GetType)

    '                If chkMaster.Checked = True Then
    '                    str = ConfigurationManager.AppSettings("Master")
    '                    strMaster = Split(Str, ",")
    '                    Dim strMList(UBound(strMaster))
    '                    For intCount = 0 To UBound(strMaster)
    '                        DTObjects.Rows(intCount)("TableName") = strMaster(intCount)
    '                        DTObjects.Rows(intCount)("Executed") = False
    '                        DTObjects.Rows(intCount)("Select") = True
    '                        DTObjects.Rows(intCount)("Status") = ""
    '                    Next
    '                    SetProgress(2)
    '                    bBackRestore.ExecuteScriptWithDependency(DTObjects, chkMaster.Checked, chkTrans.Checked)
    '                    SetProgress(8)
    '                End If

    '                If chkTrans.Checked = True Then

    '                    str1 = ConfigurationManager.AppSettings("Transaction")
    '                    strTrans = Split(str1, ",")
    '                    Dim strTList(UBound(strTrans))
    '                    For intCount = 0 To UBound(strTrans)
    '                        DTObjects.Rows(intCount)("TableName") = strTrans(intCount)
    '                        DTObjects.Rows(intCount)("Executed") = False
    '                        DTObjects.Rows(intCount)("Select") = True
    '                        DTObjects.Rows(intCount)("Status") = ""
    '                    Next
    '                    SetProgress(2)
    '                    bBackRestore.ExecuteScriptWithDependency(DTObjects, chkMaster.Checked, chkTrans.Checked)
    '                    SetProgress(8)
    '                End If

    '                If chkMaster.Checked = False And chkTrans.Checked = False Then
    '                    Dim DS As New DataSet
    '                    DS.ReadXml(txtBackupDir.Text + "SQLScripts.xml")
    '                    If DS.Tables.Count > 0 Then
    '                        Dim DTObjects As DataTable = DS.Tables(0)
    '                        Dim i As Integer
    '                        DTObjects.Columns.Add("Executed", False.GetType)
    '                        DTObjects.Columns.Add("Select", False.GetType)
    '                        DTObjects.Columns.Add("Status")
    '                        For i = 0 To DTObjects.Rows.Count - 1
    '                            DTObjects.Rows(i)("Executed") = False
    '                            DTObjects.Rows(i)("Select") = False
    '                            DTObjects.Rows(i)("Status") = ""
    '                        Next
    '                        SetProgress(2)
    '                        GetSelectedObjects(DTObjects, dgTables, "TableName")
    '                        bBackRestore.ExecuteScriptWithDependency(DTObjects, chkMaster.Checked, chkTrans.Checked)
    '                        SetProgress(8)
    '                    End If
    '                End If
    '            End If
    '        End If

    '        If chkData.Checked Then
    '            Restore_Data()
    '        End If
    '        My.Computer.FileSystem.DeleteDirectory(txtBackupDir.Text, FileIO.DeleteDirectoryOption.DeleteAllContents)
    '        MessageBox.Show("Database restore complete", "Restore Complete", MessageBoxButtons.OK, MessageBoxIcon.Information)
    '    Catch ex As Exception
    '        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
    '    End Try
    'End Sub
    'Sub GetSelectedObjects(ByRef DTObjects As DataTable, ByRef dg As DataGridView, ByRef ObjectNameColumn As String)
    '    Dim i As Integer
    '    If Not IsNothing(dg.DataSource) Then
    '        Dim dt As DataTable = dg.DataSource
    '        For i = 0 To DTObjects.Rows.Count - 1
    '            dt.DefaultView.RowFilter = ObjectNameColumn + "='" + DTObjects.Rows(i)("ObjectName") + "'"
    '            If dt.DefaultView.Count > 0 Then
    '                DTObjects.Rows(i)("Select") = dt.DefaultView(0)("Select")
    '            End If
    '        Next
    '        dt.DefaultView.RowFilter = Nothing
    '    End If
    'End Sub

    'Sub Restore_Data()
    '    Try
    '        Dim intRows As Integer
    '        If Not IsNothing(dgTables.DataSource) Then
    '            Dim DT As DataTable = CType(dgTables.DataSource, DataTable)
    '            SetProgress(0)
    '            ProgressBar1.Maximum = DT.Rows.Count - 1
    '            For intRows = 0 To DT.Rows.Count - 1
    '                If DT.Rows(intRows)("select") = True Then
    '                    Try
    '                        DT.Rows(intRows)("status") = bBackRestore.ImportData(DT.Rows(intRows)("TableName"), txtBackupDir.Text, chkDeleteExistingData.Checked)
    '                    Catch ex As Exception
    '                        MsgBox(ex.ToString)
    '                    End Try
    '                End If
    '                SetProgress(intRows)
    '            Next
    '        End If
    '    Catch ex As Exception
    '        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
    '    End Try
    'End Sub

End Class